//
//  SUNBaseViewController.swift
//  SUNweibo
//
//  Created by sighting on 16/8/21.
//  Copyright © 2016年 sighting. All rights reserved.
//

import UIKit

class SUNBaseViewController: UIViewController {
    //
    var isPull = false
    
    // tableView
    var tabView:UITableView?
    // 下拉刷新
//    let refresh:UIRefreshControl?
    var refresh:UIRefreshControl?
    
    // 自定义navigationBar
    lazy var navigationbar = UINavigationBar(frame:CGRect(x: 0, y: 0, width: UIScreen.main().bounds.width, height:64))
    
    // 自定义NavigationItem
    lazy var navItem = UINavigationItem()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setUI()
        // 加载数据源方法
        LoadData()
    }
    
    //MARK:LoadData()
    func LoadData(){
        
    }
    
    // 重写title
    override var title: String?{
        didSet{
        navItem.title = title
        }
    }
}

// 设置界面
extension SUNBaseViewController{

    // MARK:setUI
    func setUI() {
        
        view.backgroundColor = UIColor.colorWithRandom()
        
        // 抽取添加navigationbar方法
        setUpNavigationbar()
        
        // 添加tabView
        setUpTabView()
        
    }
    
    // MARK:setUpRefresh
//    private func setUpRefresh(){
//    
//        refresh = UIRefreshControl(frame:)
//    
//    }
    
    // MARK:setUpTabView
    private func setUpTabView(){
    
        tabView = UITableView(frame: view.bounds, style: .plain)
        tabView?.dataSource = self
        tabView?.delegate = self
        
        view.insertSubview(tabView!, belowSubview: navigationbar)
    }
    
    // MARK:setUpNavigationbar
    private func setUpNavigationbar(){
    
        view.addSubview(navigationbar)
        navigationbar.items = [navItem]
        
        navigationbar.titleTextAttributes = [NSForegroundColorAttributeName:UIColor.darkGray()]
        // 设置navigationbar标题颜色
        navigationbar.barTintColor = UIColor.init(colorLiteralRed: 249, green: 249, blue: 249, alpha: 1)
    }

}

// 实现方法UITableViewDataSource,UITableViewDelegate方法
extension SUNBaseViewController:UITableViewDataSource,UITableViewDelegate {

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 0
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        return UITableViewCell()
    }
    
    // 滚动到最后一行开始刷新
    func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        
        let row = indexPath.row
        
        let section = (tabView?.numberOfSections)! - 1
        
        if row<0||section<0 {
            return
        }
        
        let count  = tabView?.numberOfRows(inSection: section)
        
        if row == (count!-1) && !isPull {
            
            isPull = true
            LoadData()
            
        }
        
    }


}
